package com.songcha.module_mine.ui.activity.unregister

import android.graphics.Color
import android.os.Bundle
import android.view.View
import com.alibaba.android.arouter.launcher.ARouter
import com.songcha.library_base.mvvm.base.BaseMvvmActivity
import com.songcha.library_business.LibraryBusinessApplication
import com.songcha.library_business.config.FunctionConfig
import com.songcha.library_business.event.wx.WXLoginRespEvent
import com.songcha.library_business.helper.WxHelper
import com.songcha.library_business.provider.IClearToMainActivityProvider
import com.songcha.library_business.proxy.userinfo.UserInfoManager
import com.songcha.library_business.util.BusinessJumpUtil
import com.songcha.library_common.util.JumpUtil
import com.songcha.library_common.util.RegexUtil
import com.songcha.library_common.util.ToastUtil
import com.songcha.module_mine.R
import com.songcha.module_mine.databinding.MineActivityUnregisterBinding
import com.songcha.module_mine.ui.activity.MainActivity
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.util.concurrent.TimeUnit

class UnRegisterAccountActivity:BaseMvvmActivity<UnRegisterAccountViewModel,MineActivityUnregisterBinding>() {
    private var mSendVerifyDispose: Disposable?=null

    override fun getLayoutId(): Int {
        return R.layout.mine_activity_unregister
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        if(FunctionConfig.IS_WX_LOGIN_ENABLED && UserInfoManager.checkLogin() && UserInfoManager.userInfo!!.registeredSource==2){
            databinding.mineLlTypePhone.visibility=View.GONE
            databinding.mineLlTypeWx.visibility=View.VISIBLE
            viewModel.registerType=2
        }

        databinding.mineIvBack.setOnClickListener {
            finish()
        }

        databinding.mineBtnUnregister.setOnClickListener{
            unregister()
        }

        databinding.mineTvSendVerify.setOnClickListener {
            sendVerify()
        }

        databinding.mineBtnUnregisterSuccess.setOnClickListener{
            ARouter.getInstance().build("/main/ClearToMainActivityImpl").navigation()?.let {
                it as IClearToMainActivityProvider
                it.clearToMain(false)
            }
        }

        viewModel.verifyCountDown.observe(this){data->
            updateTvSendVerify(data)
        }

        viewModel.sendVerifySuccess.observe(this){data->
            showSendVerifyResult(data)
        }

        viewModel.unregisterState.observe(this){data->
            if(data){
                databinding.mineLlVerifyPhone.visibility= View.GONE
                databinding.mineLlUnregisterSuccess.visibility= View.VISIBLE
            }
        }

        EventBus.getDefault().register(this)

    }

    private fun unregister(){
        if(viewModel.registerType==1){
            val phone=databinding.mineEdtPhone.text.toString().trim()
            if(!checkPhone(phone)) return
            val code=databinding.mineEdtVerify.text.toString().trim()
            if(code.isBlank()) return
            viewModel.unregister(phone,code)
        }else{
            WxHelper.wxlogin()
        }

    }

    private fun updateTvSendVerify(countDown:Int){
        if(countDown==0){
            databinding.mineTvSendVerify.text="发送验证码"
            //databinding.mineTvSendVerify.setTextColor(Color.parseColor("#635F5F"))
        }else{
            databinding.mineTvSendVerify.text="重新获取（${countDown}s）"
            //databinding.mineTvSendVerify.setTextColor(Color.parseColor("#6D90E0"))
        }

    }

    private fun showSendVerifyResult(isSuccess: Boolean){
        if(isSuccess){
            ToastUtil.show("验证码发送成功")
        }else{
            mSendVerifyDispose?.dispose()
        }
    }

    private fun sendVerify(){
        if(viewModel.verifyCountDown.value!!>0){
            return
        }

        val phone=databinding.mineEdtPhone.text.toString().trim()
        if(!checkPhone(phone)) return

        mSendVerifyDispose?.dispose()
        mSendVerifyDispose = Observable.intervalRange(0,60,0,1, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe{
                viewModel.setCountDown(59-it.toInt())
            }

        viewModel.sendVerify(phone)
    }

    private fun checkPhone(phone:String):Boolean{
        if(phone.isEmpty()){
            ToastUtil.show(resources.getString(R.string.mine_please_input_origin_phone))
            return false
        }
        if(!RegexUtil.isPhone(phone)){
            ToastUtil.show(resources.getString(R.string.mine_invalid_phone))
            return false
        }
        if(UserInfoManager.userInfo!=null && phone!= UserInfoManager.userInfo!!.phonenumber){
            ToastUtil.show("原手机号码不正确")
            return false
        }
        return true
    }

    @Subscribe
    fun onWXLoginResp(event: WXLoginRespEvent){
        if(event.errCode==0){
            viewModel.unregisterByWx(event.code)
        }else if(event.errCode==-2){
            ToastUtil.show("用户取消微信登录")
        }else{
            ToastUtil.show("微信登录异常")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}